<?php
namespace App\Admin\Controllers\Reimburse;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\AmazonCountry;
use App\Models\Product\ProductClassify;
use App\Models\Reimburse\ReimburseApply;
use App\Models\Reimburse\ReimburseDetail;
use App\Util\ListPermission;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Support\Facades\Request;

class DetailController extends AdminController{

    protected $title = '返款明细';

    protected function grid()
    {
        $grid = new Grid(new ReimburseDetail());
        $grid = ListPermission::gridCountry($grid);
        $grid->model()->orderBy('id', 'DESC');
        $grid->column('paid_status','付款状态')->using(ReimburseApply::$_paidStatus)->totalRow('TTL');
        $grid->column('report_date','核算月');
        $grid->column('fee_type','费用类型')->using(ReimburseApply::$_feeType);
        $grid->column('r_type','刷单类型')->using(ReimburseApply::$_rType);
        $grid->column('order_no','订单号/费用描述');
        $grid->column('country.country','国家');
        $grid->column('seller_id','销售')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('seller_sku','平台SKU');
        $grid->column('sku.psku_code','SKU');
        $grid->column('sku.psku_cn','产品名称');
        $grid->column('skuClassify.title','品类');
        $grid->column('paid_method','支付方式')->using(ReimburseApply::$_paidMethod);
        $grid->column('paid_account_no','支付账号');
        $grid->column('currency_code','币种');
        $grid->column('rate_odds','支付汇率');
        $grid->column('order_atten','订单联系人');
        $grid->column('remarks','备注')->limit(30);
        $grid->column('currency_code_4','佣金币种');
        $grid->column('rate_odds_4','佣金支付汇率');
        $grid->column('paid_method_4','佣金支付方式')->using(ReimburseApply::$_paidMethod);
        $grid->column('paid_account_no_4','佣金账号');
        $grid->column('paid_amount_1','一次性返款');
        $grid->column('paid_amount_2','首次返款');
        $grid->column('paid_amount_3','二次返款');
        $grid->column('paid_date','付款时间');
        $grid->column('paid_amount_4','佣金');
        $grid->column('paid_date_4','佣金付款时间');
        $grid->column('r_rate_odds','收款汇率');
        $grid->column('r_currency_code','收款货币');
        $grid->column('r_amount','收款（原币）');
        $grid->column('r_amount_rmb','收款RMB')->totalRow();
        $grid->column('fulfillment_type','配送方式')->using(ReimburseDetail::$_fulfillmentType);
        $grid->column('purchase_price_rmb','采购成本')->totalRow();
        $grid->column('shipment_price_rmb','运费')->totalRow();
        $grid->column('amount_rmb','刷单费用RMB')->totalRow();

        $grid->disableActions();
        $grid->disableRowSelector();
        $grid->disableCreateButton();
        $grid->paginate(10);
        $grid->fixColumns(1,0);
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('reimburse/detail-download'));
        });
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter) {
                $filter->between('report_date','核算月')->datetime(['format' => 'YYYY-MM-01']);
                $filter->like('paid_account_no', '支付账号');
                $filter->where(function ($query) {
                    $query->whereIn('order_no', explode(',',"{$this->input}"));
                }, '订单号','orderNo');
                $filter->equal('country_id','国家')->select(AmazonCountry::options());
            });
            $filter->column(1/3, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
                $filter->equal('fee_type','费用类型')->select(ReimburseApply::$_feeType);
                $filter->equal('r_type','刷单类型')->select(ReimburseApply::$_rType);
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('seller_id','销售')->select(User::getSellerOptions());
                $filter->equal('paid_status','付款状态')->select(ReimburseApply::$_paidStatus);
                $filter->equal('fulfillment_type', '配送方式')->select(ReimburseDetail::$_fulfillmentType);
            });
        });
        return $grid;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = ReimburseDetail::query()->orderBy('id', 'DESC');
        $query = ListPermission::country($query);
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('classify_id', $_filter['classify_id']);
                });
            }
            if($key == 'paid_account_no'){
                $query->where(function ($query) use($_filter){
                    $query->where('paid_account_no', 'like', "%{$_filter}%");
                });
            }
            if($key == 'orderNo'){
                $query->whereIn('order_no', explode(',',"{$_filter}"));
            }
            if($key == 'report_date'){
                if(isset($_filter['start'])&&$_filter['start']){
                    $query->where('report_date','>=',$_filter['start']);
                }
                if(isset($_filter['end'])&&$_filter['end']){
                    $query->where('report_date','<=',$_filter['end']);
                }
            }
            if(in_array($key,['country_id','fee_type','r_type','seller_id','fulfillment_type','paid_status'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['付款状态','核算月','费用类型','刷单类型','订单号/费用描述','提报单号','国家','销售员',
            '亚马逊SKU','公司SKU','产品名称','品类','支付方式','支付账号','币种','支付汇率','订单联系人','备注',
            '佣金币种','佣金支付汇率','佣金支付方式','佣金账号','一次性返款','首次返款','二次返款','支付返款RMB','付款时间',
            '佣金','支付佣金RMB','佣金付款时间','合计支付RMB','收款汇率','收款货币','收款（原币）','收款RMB','配送方式','采购成本','运费','刷单费用RMB'];
        RExcel::exportCsv('返款明细',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::_getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    private static function _getDownloadData($res)
    {
        $seller = [];
        foreach ($res as $model){
            $sellerId = $model->seller_id ?? 0;
            if(!array_key_exists($sellerId,$seller)){
                $seller[$sellerId] = User::getUsernameById($sellerId);
            }
            $paid_amount_rmb = numberFormat($model->rate_odds * ($model->paid_amount_1 + $model->paid_amount_2 + $model->paid_amount_3));
            $paid_amount_rmb_4 = numberFormat($model->rate_odds_4 * $model->paid_amount_4);
            $temp = [
                ReimburseApply::$_paidStatus[$model->paid_status],
                $model->report_date,
                ReimburseApply::$_feeType[$model->fee_type],
                ReimburseApply::$_rType[$model->r_type],
                $model->order_no,
                $model->reimburse_no,
                $model->country->country ?? '',
                $seller[$sellerId],
                $model->seller_sku ?: '',
                $model->sku->psku_code ?? '',
                $model->sku->psku_cn ?? '',
                $model->skuClassify->title ?? '',
                ReimburseApply::$_paidMethod[$model->paid_method],
                $model->paid_account_no,
                $model->currency_code,
                $model->rate_odds,
                $model->order_atten,
                $model->remarks ,
                $model->currency_code_4,
                $model->rate_odds_4,
                $model->paid_method_4 ? ReimburseApply::$_paidMethod[$model->paid_method_4] : '',
                $model->paid_account_no_4,
                $model->paid_amount_1,
                $model->paid_amount_2,
                $model->paid_amount_3,
                $paid_amount_rmb,
                $model->paid_date,
                $model->paid_amount_4,
                $paid_amount_rmb_4,
                $model->paid_date_4,
                numberFormat($paid_amount_rmb + $paid_amount_rmb_4),
                $model->r_rate_odds,
                $model->r_currency_code,
                $model->r_amount,
                $model->r_amount_rmb,
                $model->fulfillment_type ? ReimburseDetail::$_fulfillmentType[$model->fulfillment_type] : '',
                $model->purchase_price_rmb,
                $model->shipment_price_rmb,
                $model->amount_rmb,
            ];
            yield $temp;
        }
    }
}
